package cmd

import (
	"context"
	"fmt"
	"github.com/spf13/cobra"
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/nami/config"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"strconv"
	"strings"
	"time"
)

var deleteMatchCli = &cobra.Command{
	Use:   "delete_match",
	Short: "test cronjob server",
	Long:  "test cronjob server",
	Run: func(cmd *cobra.Command, args []string) {

		names, err := global2.GetEs().IndexNames()
		if err != nil {
			global2.Log.Errorf("get index error:%v", err)
			return
		}
		ids := make([]int, 0)
		for _, name := range names {
			split := strings.Split(name, "match_live_text_")
			if len(split) == 2 {
				id, _ := strconv.Atoi(split[1])
				ids = append(ids, id)
			}
		}
		if len(ids) > 0 {
			data := models_sports.MatchTempSchedule{}
			records := make([]int, 0)
			err = global2.Sport().
				Model(&data).
				Where("match_id in ?", ids).
				Where("match_time <= ? ", time.Now().AddDate(0, 0, -7).Unix()).
				Pluck("match_id", &records).Error
			if err != nil {
				global2.Log.Errorf("get index error:%v", err)
				return
			}
			deleteIndex := make([]string, 0)
			for _, record := range records {
				deleteIndex = append(deleteIndex, fmt.Sprintf("match_live_text_%d", record))
			}

			ctx := context.Background()

			delete := make([]string, 0)
			for _, index := range deleteIndex {
				delete = append(delete, index)
				if len(delete) == 100 {
					_, err := global2.GetEs().DeleteIndex(delete...).Do(ctx)
					if err != nil {
						global2.Log.Errorf("delete indexs : %v", err)
					}
					delete = []string{}
				}
			}

			if len(delete) > 0 {
				_, err := global2.GetEs().DeleteIndex(delete...).Do(ctx)
				if err != nil {
					global2.Log.Errorf("delete indexs : %v", err)
				}
			}

		}

	},
	PreRun: func(cmd *cobra.Command, args []string) {
		global2.Initialize(configFile)
		config.InitConfig()

		err := global2.InitElasticSearch()
		if err != nil {
			global2.Log.Fatalf("%s", err.Error())
		}
	},
	PostRun: func(cmd *cobra.Command, args []string) {

	},
}

func deleteMatch(data []models_sports.MatchTempSchedule) {
	//bulks := make([]*elastic.BulkDeleteRequest, 0)
	//
	//total := 3000 // 3000条批量写一次
	//writeCount := 0
	//for _, datum := range data {
	//	// 赛程ID+timehelper
	//	id := fmt.Sprintf("%d-%s", datum.MatchId, datum.Time)
	//	bulks = append(bulks, elastic.BulkIndexRequest{}().Index(t.getEsIndexName()).Type("doc").Doc(datum).Id(id))
	//	writeCount++
	//	if writeCount == total {
	//		bulks.bulkToEs(bulks)
	//		bulks = make([]*elastic.BulkIndexRequest, 0)
	//	}
	//}
	//
	//if len(bulks) > 0 {
	//	t.bulkToEs(bulks)
	//}
}
